#include <my_head.h>

int main(int argc, const char *argv[])
{
	char sqlbuff[512] = {0};
	sqlite3 *my_db = NULL;
	// 打开数据库
	sqlite3_open("xja.db", &my_db);
	// 删除原表
	strcpy(sqlbuff, "DROP TABLE dict");
	sqlite3_exec(my_db, sqlbuff, NULL, NULL, NULL);
	// 创建新表
	strcpy(sqlbuff, "CREATE TABLE dict(word TEXT PRIMARY KEY, explanation TEXT)");
	sqlite3_exec(my_db, sqlbuff, NULL, NULL, NULL);
	
	int count = 0;
	// 打开词库文件
	FILE *fp = fopen("dict.txt", "r");
	// 循环读取单词 插入数据库
	char buff[256] = {0};
	char word[64] = {0};
	char explanation[256] = {0};
	int i = 0;
	int j = 0;
	while(NULL != fgets(buff, sizeof(buff), fp)){
		// buff[strlen(buff) - 2] = '\0';
		// i = 0;
		// 将 one's 改成 one.s
		// while('\0' != buff[i]){
		// 	if('\'' == buff[i]){
		// 		buff[i] = '.';
		// 	}
		// 	i++;
		// }
		// 截取单词和解释
		i = 0;
		while(' ' != buff[i]){
			if('\'' == buff[i]){
				buff[i] = '.';
			}
			word[i] = buff[i];
			i++;
		}
		word[i] = '\0';
		while(' ' == buff[i])i++;
		//strcpy(explanation, buff+i);
		j = 0;
		while('\0' != buff[i] && '\r' != buff[i]){
			if('\'' == buff[i]){
				buff[i] = '.';
			}
			explanation[j++] = buff[i++];
		}
		explanation[j] = '\0';
		// 插入数据库
		printf("正在导入第 [%8d] 个--单词:[%s] 解释:[%s]\n", ++count, word, explanation);
		// 组装sql语句
		sprintf(sqlbuff, "INSERT INTO dict VALUES('%s', '%s')", word, explanation);
		// 执行
		sqlite3_exec(my_db, sqlbuff, NULL, NULL, NULL);
		//usleep(1);
		//memset(buff, 0, sizeof(buff));
	} 
	
	return 0;
}
